package admin

import (
	"invitation/internal/application"
	"invitation/internal/http/middleware"
	"invitation/internal/http/utils"
	"invitation/internal/model"
	"invitation/internal/pojo/dto"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

func UpdateGameEndpoint(application *application.Application) func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		gameReq := ctx.Locals(middleware.LocalKeysGameCreateRequest).(*dto.GamePayload)
		log.Debug().Msgf("%v", gameReq)
		if gameReq.ID == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "id is required",
			})
		}
		log.Debug().Msgf("%v", gameReq)
		id, err := utils.StringToUint(gameReq.ID)
		if err != nil {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "id is invalid",
			})
		}
		log.Debug().Msgf("%v", id)
		if _, err := application.RepoManager().GameInfoRepo().FindOneByID(id); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		// 开启事务
		txCtx, err := application.RepoManager().BeginTx(ctx.Context())
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		defer func() {
			if err != nil {
				application.RepoManager().RollbackTx(txCtx)
			} else {
				application.RepoManager().CommitTx(txCtx)
			}
		}()

		// 更新 GameInfo
		gameInfo := &model.GameInfo{}
		gameInfo.ID = id
		if gameReq.Name != "" {
			gameInfo.Name = gameReq.Name
		}
		if gameReq.Desc != "" {
			gameInfo.Desc = gameReq.Desc
		}
		if gameReq.ProblemToSolve != "" {
			gameInfo.ProblemToSolve = gameReq.ProblemToSolve
		}
		log.Debug().Msgf("endpoints.admin.game_update:gameInfo:%v", gameInfo)
		if err := application.RepoManager().GameInfoRepo().Update(gameInfo); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}

		// 如果 Introduction 不为空，则更新
		if gameReq.Introduction != "" {
			if err := application.RepoManager().GameIntroductionRepo().Update(gameInfo.ID, gameReq.Introduction); err != nil {
				return ctx.Status(500).JSON(fiber.Map{
					"message": err.Error(),
				})
			}
		}

		// 如果 TheoryExplanation 不为空，则更新
		if gameReq.TheoryExplanation != "" {
			if err := application.RepoManager().GameTheoryRepo().Update(gameInfo.ID, gameReq.TheoryExplanation); err != nil {
				return ctx.Status(500).JSON(fiber.Map{
					"message": err.Error(),
				})
			}
		}

		return ctx.Status(200).JSON(fiber.Map{
			"message": "success",
		})
	}
}
